package zy.service.wx.product.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import zy.dao.base.bra.BraDAO;
import zy.dao.base.color.ColorDAO;
import zy.dao.base.size.SizeDAO;
import zy.dao.stock.data.DataDAO;
import zy.dao.wx.product.WxProductDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.base.bra.T_Base_Bra;
import zy.entity.base.color.T_Base_Color;
import zy.entity.base.product.T_Base_Product;
import zy.entity.base.size.T_Base_Size;
import zy.entity.stock.data.T_Stock_DataView;
import zy.entity.sys.user.T_Sys_User;
import zy.entity.wx.product.T_Wx_Product;
import zy.entity.wx.product.T_Wx_ProductList;
import zy.entity.wx.product.T_Wx_ProductShop;
import zy.service.wx.product.WxProductService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.ExportTxtUtil;
import zy.util.IDUtil;
import zy.util.StringUtil;

@Service
public class WxProductServiceImpl implements WxProductService{
	@Resource
	private WxProductDAO wxProductDAO;
	
	@Resource
	private DataDAO dataDAO;
	
	@Resource
	private SizeDAO sizeDAO;
	
	@Resource
	private BraDAO braDAO;
	
	@Resource
	private ColorDAO colorDAO;
	
	@Override
	public PageData<T_Wx_Product> page(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer pageSize = (Integer)params.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)params.get(CommonUtil.PAGEINDEX);
		
		Integer totalCount = wxProductDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, pageSize, pageIndex);
		params.put(CommonUtil.START, (pageIndex-1)*pageSize);
		params.put(CommonUtil.END, pageSize);
		
		List<T_Wx_Product> list = wxProductDAO.list(params);
		PageData<T_Wx_Product> pageData = new PageData<T_Wx_Product>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@Override
	public T_Wx_Product load(Integer wp_id) {
		T_Wx_Product product = wxProductDAO.load(wp_id);
		product.setWp_desc(ExportTxtUtil.txt2String(CommonUtil.CHECK_BASE+CommonUtil.WXPRODUCT_TXT_PATH + "/" + product.getWp_id() + ".txt"));
		return product;
	}
	
	@Override
	public List<T_Wx_ProductShop> loadProductShop(String ps_number,Integer companyid) {
		return wxProductDAO.loadProductShop(ps_number, companyid);
	}
	
	@Override
	public PageData<T_Base_Product> page_product(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer pageSize = (Integer)params.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)params.get(CommonUtil.PAGEINDEX);
		
		Integer totalCount = wxProductDAO.count_product(params);
		PageInfo pageInfo = new PageInfo(totalCount, pageSize, pageIndex);
		params.put(CommonUtil.START, (pageIndex-1)*pageSize);
		params.put(CommonUtil.END, pageSize);
		
		List<T_Base_Product> list = wxProductDAO.list_product(params);
		PageData<T_Base_Product> pageData = new PageData<T_Base_Product>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@Override
	@Transactional
	public void save(List<T_Wx_Product> products, T_Sys_User user) {
		String wp_shop_code = null;
		if (CommonUtil.ONE.equals(user.getShoptype())
				|| CommonUtil.TWO.equals(user.getShoptype())
				|| CommonUtil.FOUR.equals(user.getShoptype())) {// 总公司、分公司、加盟
			wp_shop_code = user.getUs_shop_code();
		}else{//自营、合伙
			wp_shop_code = user.getShop_upcode();
		}
		List<String> pdCodes = new ArrayList<String>();
		for (T_Wx_Product product : products) {
			pdCodes.add(product.getPd_code());
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(CommonUtil.COMPANYID, user.getCompanyid());
		params.put(CommonUtil.SHOP_CODE, wp_shop_code);
		params.put("pdCodes", pdCodes);
		int existCount = wxProductDAO.checkExist(params);
		if (existCount > 0) {
			throw new RuntimeException("录入货号已发布，请重新选择！");
		}
		String[] numbers = IDUtil.buildNumber(products.size());
		int index = 0;
		List<T_Wx_ProductList> productLists = new ArrayList<T_Wx_ProductList>();
		List<T_Wx_ProductShop> productShops = new ArrayList<T_Wx_ProductShop>();
		for (T_Wx_Product product : products) {
			product.setWp_number(numbers[index++]);
			product.setWp_shop_code(wp_shop_code);
			product.setWp_weight(0);
			product.setWp_likecount(0);
			product.setWp_browse_count(0);
			product.setWp_sell_amount(0);
			product.setWp_state(0);
			product.setWp_sysdate(DateUtil.getCurrentTime());
			product.setCompanyid(user.getCompanyid());
			//商品属性
			String propertyCodes = product.getWp_property_code();
			if (StringUtil.isNotEmpty(propertyCodes)) {
				String[] propertyArr = propertyCodes.split(",");
				for(String property:propertyArr){
					T_Wx_ProductList productList = new T_Wx_ProductList();
					productList.setPl_number(product.getWp_number());
					productList.setPl_code(property);
					productList.setPl_type(0);
					productList.setCompanyid(user.getCompanyid());
					productLists.add(productList);
				}
			}
			//售后承诺
			String promiseCodes = product.getWp_promise_code();
			if(StringUtil.isNotEmpty(promiseCodes)){
				String[] promiseArr = promiseCodes.split(",");
				for (String promise : promiseArr) {
					T_Wx_ProductList productList = new T_Wx_ProductList();
					productList.setPl_number(product.getWp_number());
					productList.setPl_code(promise);
					productList.setPl_type(1);
					productList.setCompanyid(user.getCompanyid());
					productLists.add(productList);
				}
			}
			//关联店铺
			String shopCodes = product.getShop_codes();
			if (StringUtil.isNotEmpty(shopCodes)) {
				String[] shopArr = shopCodes.split(",");
				for (String shop : shopArr) {
					T_Wx_ProductShop productShop = new T_Wx_ProductShop();
					productShop.setPs_number(product.getWp_number());
					productShop.setPs_shop_code(shop);
					productShop.setCompanyid(user.getCompanyid());
					productShops.add(productShop);
				}
			}
		}
		wxProductDAO.save(products, productLists, productShops);
	}
	
	@Override
	@Transactional
	public void update(T_Wx_Product product, T_Sys_User user) {
		wxProductDAO.update(product);
		List<T_Wx_ProductList> productLists = new ArrayList<T_Wx_ProductList>();
		if(StringUtil.isNotEmpty(product.getWp_property_code())){
			String[] propertyArr = product.getWp_property_code().split(",");
			for(String property:propertyArr){
				T_Wx_ProductList productList = new T_Wx_ProductList();
				productList.setPl_number(product.getWp_number());
				productList.setPl_code(property);
				productList.setPl_type(0);
				productList.setCompanyid(user.getCompanyid());
				productLists.add(productList);
			}
			wxProductDAO.delProductList(product.getWp_number(), 0, user.getCompanyid());
		}
		if(StringUtil.isNotEmpty(product.getWp_promise_code())){
			String[] promiseArr = product.getWp_promise_code().split(",");
			for (String promise : promiseArr) {
				T_Wx_ProductList productList = new T_Wx_ProductList();
				productList.setPl_number(product.getWp_number());
				productList.setPl_code(promise);
				productList.setPl_type(1);
				productList.setCompanyid(user.getCompanyid());
				productLists.add(productList);
			}
			wxProductDAO.delProductList(product.getWp_number(), 1, user.getCompanyid());
		}
		if (productLists.size() > 0) {
			wxProductDAO.saveProductList(productLists);
		}
		ExportTxtUtil.string2Txt(StringUtil.trimString(product.getWp_desc()),
				CommonUtil.CHECK_BASE+CommonUtil.WXPRODUCT_TXT_PATH + "/" + product.getWp_id() + ".txt");
	}

	@Override
	@Transactional
	public void updateState(Map<String, Object> params) {
		wxProductDAO.updateState(params);
	}
	
	@Override
	@Transactional
	public void updateShop(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		String wp_number = (String)params.get("wp_number");
		String shop_codes = (String)params.get("shop_codes");
		List<T_Wx_ProductShop> productShops = wxProductDAO.loadProductShop(wp_number, companyid);
		List<String> existShopCodes = new ArrayList<String>();
		List<String> newShopCodes = new ArrayList<String>();
		for (T_Wx_ProductShop item : productShops) {
			existShopCodes.add(item.getPs_shop_code());
		}
		if(StringUtil.isNotEmpty(shop_codes)){
			newShopCodes.addAll(Arrays.asList(shop_codes.split(",")));
		}
		List<T_Wx_ProductShop> addProductShops = new ArrayList<T_Wx_ProductShop>();
		List<String> delShops = new ArrayList<String>();
		if (existShopCodes.size() > 0 && newShopCodes.size() > 0) {
			for (String code : existShopCodes) {
				if(!newShopCodes.contains(code)){
					delShops.add(code);
				}
			}
			for (String code : newShopCodes) {
				if(!existShopCodes.contains(code)){
					T_Wx_ProductShop item = new T_Wx_ProductShop();
					item.setCompanyid(companyid);
					item.setPs_number(wp_number);
					item.setPs_shop_code(code);
					addProductShops.add(item);
				}
			}
		}else if(existShopCodes.size()>0){
			delShops.addAll(existShopCodes);
		}else if(newShopCodes.size()>0){
			for (String code : newShopCodes) {
				T_Wx_ProductShop item = new T_Wx_ProductShop();
				item.setCompanyid(companyid);
				item.setPs_number(wp_number);
				item.setPs_shop_code(code);
				addProductShops.add(item);
			}
		}
		if (addProductShops.size() > 0) {//新增
			wxProductDAO.saveProductShop(addProductShops);
		}
		if (delShops.size() > 0) {//删除
			wxProductDAO.delProductShop(delShops, wp_number, companyid);
		}
	}
	
	@Override
	@Transactional
	public void del(Map<String, Object> params) {
		wxProductDAO.del(params);
	}

	@Override
	public List<T_Wx_Product> hot_sell(Map<String, Object> params) {
		Assert.notNull(params.get(CommonUtil.COMPANYID), "连接超时，请重新登录!");
		Assert.notNull(params.get(CommonUtil.SHOP_TYPE), "参数shop_type不能为null");
		Assert.notNull(params.get(CommonUtil.SHOP_CODE), "参数shop_code不能为null");
		Assert.notNull(params.get(CommonUtil.SHOP_UPCODE), "参数shop_upcode不能为空!");
		Assert.notNull(params.get(CommonUtil.PAGESIZE), "参数pageSize不能为空!");
		Assert.notNull(params.get(CommonUtil.PAGEINDEX), "参数pageIndex不能为空!");
		Integer pageSize = (Integer)params.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)params.get(CommonUtil.PAGEINDEX);
		params.put(CommonUtil.START, (pageIndex-1)*pageSize);
		params.put(CommonUtil.END, pageSize);
		return wxProductDAO.hot_sell(params);
	}
	
	@Override
	public List<T_Wx_Product> listByType(Map<String, Object> params) {
		Assert.notNull(params.get(CommonUtil.COMPANYID), "连接超时，请重新登录!");
		Assert.notNull(params.get(CommonUtil.SHOP_TYPE), "参数shop_type不能为null");
		Assert.notNull(params.get(CommonUtil.SHOP_CODE), "参数shop_code不能为null");
		Assert.notNull(params.get(CommonUtil.SHOP_UPCODE), "参数shop_upcode不能为空!");
		Assert.notNull(params.get("pt_code"), "参数pt_code不能为空!");
		Assert.notNull(params.get(CommonUtil.PAGESIZE), "参数pageSize不能为空!");
		Assert.notNull(params.get(CommonUtil.PAGEINDEX), "参数pageIndex不能为空!");
		Integer pageSize = (Integer)params.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)params.get(CommonUtil.PAGEINDEX);
		params.put(CommonUtil.START, (pageIndex-1)*pageSize);
		params.put(CommonUtil.END, pageSize);
		return wxProductDAO.listByType(params);
	}
	
	@Override
	public T_Wx_Product load(String pd_code,String shop_code,Integer companyid) {
		T_Wx_Product product = wxProductDAO.load(pd_code,shop_code,companyid);
		if (product != null) {
			product.setWp_desc(ExportTxtUtil.txt2String(CommonUtil.CHECK_BASE+CommonUtil.WXPRODUCT_TXT_PATH + "/" + product.getWp_id() + ".txt"));
		}
		return product;
	}
	
	@Override
	public Map<String, Object> loadStock(Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<T_Base_Color> colors = colorDAO.queryByPdCode(params);
		List<T_Base_Bra> bras = braDAO.queryByPdCode(params);
		List<T_Base_Size> sizes = dataDAO.querySizeByPdCode(params);
		List<T_Stock_DataView> data = dataDAO.queryByPdCode(params);
		resultMap.put("color", colors);
		resultMap.put("bra", bras);
		resultMap.put("size", sizes);
		resultMap.put("stock", data);
		return resultMap;
	}
	
	@Override
	public Map<String, Object> loadStock_Wx(Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<T_Base_Color> colors = colorDAO.queryByPdCode(params);
		List<T_Base_Bra> bras = braDAO.queryByPdCode(params);
		List<T_Base_Size> sizes = dataDAO.querySizeByPdCode(params);
		List<T_Stock_DataView> data = dataDAO.queryByPdCode(params);
		List<String> imgs = wxProductDAO.listProductImgs(params);
		if (imgs.size() > 0) {
			for (int i = 0; i < imgs.size(); i++) {
				imgs.set(i, CommonUtil.FTP_SERVER_PATH+imgs.get(i));
			}
		}
		resultMap.put("stock", data);
		resultMap.put("color", colors);
		resultMap.put("imgs", imgs);
		resultMap.put("size", sizes);
		resultMap.put("bra", bras);
		return resultMap;
	}
	
}
